import fsPromises from 'fs/promises';
import path from 'path';  
class Common {
    /** */
    static msleep ( time ) {
        return new Promise(( resolve ) => {
            setTimeout(resolve, time);
        });
    }

    /** 判断变量是否为空 */
    static isVarEmpty( value ) {
        let isEmpty = undefined == value;
        isEmpty = isEmpty || ( 'object' == typeof(value) && 0 == Object.keys(value).length );
        isEmpty = isEmpty || ( 'string' == typeof(value) && '' == value );
        return isEmpty;
    }

    // 判断文件是否存在
    static async isFileExists( path ) {
        try {
            await fsPromises.access(path, fsPromises.F_OK);
            return true;
        } catch {
            return false;
        }
    }
    
    // 读取文件内容
    static async fileGetContent( path ) {
        return await fsPromises.readFile(path,{encoding:'utf8'});
    }

    // 写入文件内容
    static async filePutContent( path, content ) {
        await fsPromises.writeFile(path, content);
    }

    // 创建文件夹
    static async dirCreateIfNotExists( dir ) {
        let parent = path.dirname(dir);
        if ( ! await Common.isFileExists(parent) ) {
            await Common.dirCreateIfNotExists(parent);
        }
        if ( ! await Common.isFileExists(dir) ) {
            await fsPromises.mkdir(dir);
        }
    }
}

export default Common;